<template>
    <div>
        <!-- 查询表单 -->
        <a-card :bordered="false">
            <DynamicFormSearch
                :form-items="formItems"
                :initial-values="searchForm"
                @submit="handleSearch"
                @reset="handleReset"
            />
        </a-card>
        <!-- 表格 -->
        <a-card :bordered="false" class="mt-4">
            <a-button type="primary" @click="handleAdd" class="mb-4">新增</a-button>

            <a-table
                :columns="columns"
                :data-source="list"
                :pagination="pagination"
                :loading="loading"
                @change="handleTableChangeForPaging"
            >
                <template #bodyCell="{ column, record }">
                    <template v-if="column.dataIndex === 'avatar'">
                        <a-avatar :src="record.avatar" :icon="!record.avatar ? h(UserOutlined) : undefined" />
                    </template>
                    <template v-if="column.dataIndex === 'gender'">
                        <template v-if="record.gender === 'unknown'">
                            <a-tag color="default">未知</a-tag>
                        </template>
                        <template v-if="record.gender === 'male'">
                            <a-tag color="blue">男</a-tag>
                        </template>
                        <template v-if="record.gender === 'female'">
                            <a-tag color="pink">女</a-tag>
                        </template>
                    </template>

                    <template v-if="column.dataIndex === 'lastLoginIp'">
                        <a-tag color="cyan">{{
                            `${record.lastLoginIp === "::1" || record.lastLoginIp === "127.0.0.1" ? "本地" : record.lastLoginIp}`
                        }}</a-tag>
                    </template>

                    <!-- 操作列 -->
                    <template v-if="column.dataIndex === 'action'">
                        <a-space :size="8">
                            <a-button type="link" size="small" @click="handleEdit(record as any)"> 编辑 </a-button>
                            <!-- <a-button type="link" size="small" @click="handleView(record as any)"> 查看 </a-button> -->
                            <a-popconfirm
                                title="确定要删除吗？"
                                ok-text="确定"
                                cancel-text="取消"
                                @confirm="handleDelete(record as any)"
                            >
                                <a-button type="link" size="small" danger>删除</a-button>
                            </a-popconfirm>
                        </a-space>
                    </template>
                </template>
            </a-table>
        </a-card>
        <!-- 表单对话框 -->
        <FormModal v-model:open="formModalVisible" :record="tableRowRecord" @success="handleFormSuccess" />
    </div>
</template>
<script lang="ts" setup>
import { UserOutlined } from "@ant-design/icons-vue";
import { message, type TableProps } from "ant-design-vue";
import { h } from "vue";

import type { CategoryEntity, SysUserVo } from "@/api/globals";
import type { FormItemConfig } from "@/components/dynamic-form/types/form-config";
import { useAntdvPaging } from "@/hooks/useAntdvPage";
import { DateTimeUtils } from "@/utils/DateTimeUtils";

import FormModal from "./FormModal.vue";
// import FormModal from "./FormModalV1.vue";
// import FormModal from "./FormModalV2.vue";

// 表单对话框可见
const formModalVisible = ref(false);
// 表格当前行数据
const tableRowRecord = ref<SysUserVo | null>(null);

// 列表列
const columns: TableProps["columns"] = [
    {
        title: "序号",
        dataIndex: "index",
        key: "index", // 列的key，默认为dataIndex
        customRender: row => {
            // 连续序号 = (当前页码 - 1) * 每页条数 + 当前行索引 + 1
            return (page.value - 1) * pageSize.value + row.index + 1;
        },
        width: 80,
        align: "center"
    },
    {
        title: "头像",
        dataIndex: "avatar"
    },
    {
        title: "账号",
        dataIndex: "username"
    },
    {
        title: "昵称",
        dataIndex: "nickname"
    },
    {
        title: "真实姓名",
        dataIndex: "realname"
    },
    {
        title: "邮箱",
        dataIndex: "email",
        ellipsis: true,
        width: 180
    },
    {
        title: "手机号",
        dataIndex: "phone",
        ellipsis: true,
        width: 180
    },
    {
        title: "性别",
        dataIndex: "gender"
    },
    {
        title: "登录IP",
        dataIndex: "lastLoginIp",
        ellipsis: true
    },
    {
        title: "登录时间",
        dataIndex: "lastLoginAt",
        key: "lastLoginAt",
        customRender: row => DateTimeUtils.formatDateTime(row.record.lastLoginAt),
        width: 180
    },
    {
        title: "创建时间",
        dataIndex: "createdAt",
        key: "createdAt",
        customRender: row => DateTimeUtils.formatDateTime(row.record.createdAt),
        width: 180
    },
    {
        title: "操作",
        dataIndex: "action",
        key: "action",
        width: 200,
        fixed: "right",
        align: "center"
    }
];

const searchForm = reactive({
    username: "",
    nickname: "",
    realname: "",
    email: "",
    gender: void 0
});

const formItems: FormItemConfig[] = [
    {
        name: "username",
        label: "账号",
        type: "input",
        componentProps: {
            placeholder: "请输入账号"
        }
    },
    {
        name: "nickname",
        label: "昵称",
        type: "input",
        componentProps: {
            placeholder: "请输入昵称"
        }
    },
    {
        name: "realname",
        label: "真实姓名",
        type: "input",
        componentProps: {
            placeholder: "请输入真实姓名"
        }
    },
    {
        name: "email",
        label: "邮箱",
        type: "input",
        componentProps: {
            placeholder: "请输入邮箱"
        }
    },
    {
        type: "select",
        name: "gender",
        label: "性别",
        componentProps: {
            placeholder: "请选择性别",
            options: [
                {
                    label: "未知",
                    value: "unknown"
                },
                {
                    label: "男",
                    value: "male"
                },
                {
                    label: "女",
                    value: "female"
                }
            ]
        }
    }
];

const {
    list,
    loading,
    pagination,
    page,
    pageSize,
    handleReset,
    handleSearch,
    handleTableChangeForPaging,
    sendForLatestData
} = useAntdvPaging<SysUserVo>(Apis.SysUser.findListPage, searchForm);

// 表格操作

// 打开新增
const handleAdd = () => {
    tableRowRecord.value = null;
    formModalVisible.value = true;
};

// 打开编辑
const handleEdit = (record: SysUserVo) => {
    tableRowRecord.value = record;
    formModalVisible.value = true;
};

// 表单提交成功后刷新表格
const handleFormSuccess = () => {
    message.success("操作成功");
    // 重新拉取最新数据（避免缓存）
    sendForLatestData();
};

const handleView = (record: CategoryEntity) => {
    console.log("record", record);
};

const handleDelete = async (record: CategoryEntity) => {
    await Apis.CategoryAdmin.remove({
        pathParams: {
            id: record.id
        }
    });
    message.success("删除成功");
    // 添加时间参数，击穿缓存，拉取最新数据
    sendForLatestData();
};
</script>
